﻿#include <graphics.h>
#include <conio.h>
#include <stdio.h>

using namespace std;

void print_score(int score, int x, int y);

int main()
{
	float count = 0;

	int width = 600;
	int height = 400;
	initgraph(width, height);

	int radius = 10;
	int ball_x = width / 3;
	int ball_y = height - radius;
	float g = 0.6;
	float ball_speed = 0;

	int square_height = 100;
	int square_width = 20;
	int square_x = width - square_width;
	int square_y = height - square_height;
	float square_speed = -3;

	int score = 0;

	while (1)
	{
		if (_kbhit())
		{
			char c = _getch();
			if (c == ' ')
			{
				if (ball_y == height - radius)
				{
					ball_speed = -18;
				}
			}
		}
		printf("in while");
		ball_speed += g;
		ball_y += ball_speed;

		//Allow the ball to stay overground;
		if (ball_y >= height - radius)	
		{
			ball_speed = 0;
			ball_y = height - radius;
		}
		if (ball_y < radius)
		{
			ball_speed = 0;
			ball_y = radius;

		}

		square_x += square_speed;
		//Allow the square to stay overground.
		if (square_x <= 0)
		{
			score += 1;
			square_x = width;
			square_height = rand() % int(height / 4) + height / 4;
			square_speed = rand() / float(RAND_MAX) * 4 - 6;
		}

		if ((square_x <= ball_x + radius) &&
			(square_x + square_width >= ball_x - radius) &&
			(height - square_height <= ball_y + radius))
		{
			score -= 1;
			square_x = width;
			square_height = rand() % int(height / 4) + height / 4;
			square_speed = rand() / float(RAND_MAX) * 4 - 6;
		}
		cleardevice(); //Clean the canvas.
		fillcircle(ball_x, ball_y, radius); //Draw a circle.
		fillrectangle(square_x, height - square_height, square_x + square_width, height); //Draw a square.


		print_score(score, 20, 50);

		Sleep(10);	
	}
	closegraph();
	return 0;
}


void print_score(int score, int x, int y)
{
	TCHAR text[20];
	swprintf_s(text, _T("%d"), score);
	settextstyle(40, 0, _T("仿宋"));
	outtextxy(x, y, text);
}